import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
// import { MemoryInfoDocumentType } from '../schema/Memory/Memory_Schema';

@Injectable()
export class MemoryService {
  constructor(
    @InjectModel('Memory_Info')
    private MemoryInfoModel: Model<any>,
  ) {}

  async createMemoryInfo(body: any) {
    const memory_info = new this.MemoryInfoModel(body);
    console.log(memory_info);

    return memory_info.save();
  }

  async getMemoryInfo(query) {
    const { page, limit, price, type, order, capacity } = query;

    //处理排序
    let sort = {};
    if (order) {
      sort = { price: parseInt(order) };
    } else {
      sort = {};
    }

    //构建查询条件
    const filter: any = {};
    if (type) {
      filter.type = type;
    }
    if (capacity) {
      filter.capacity = capacity;
    }
    if (price) {
      if (price.min && !price.max) {
        filter.price = { $gte: price.min };
      } else if (!price.min && price.max) {
        filter.price = { $lte: price.max };
      } else if (price.min && price.max) {
        filter.price = { $gte: price.min, $lte: price.max };
      }
    }

    const result = await this.MemoryInfoModel.find(filter)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort(sort)
      .exec();
    return {
      code: 200,
      msg: 'success',
      data: {
        result,
        total: await this.MemoryInfoModel.countDocuments(filter),
      },
    };
  }

  //通过id查询内存信息
  async getMemoryInfoById(id: string) {
    const result = await this.MemoryInfoModel.findById(id).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  //更新内存信息
  async updateMemoryInfo(id: string, body: any) {
    const result = await this.MemoryInfoModel.findByIdAndUpdate(id, body, {
      new: true,
    }).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  //删除内存信息
  async deleteMemoryInfo(id: string) {
    const result = await this.MemoryInfoModel.findByIdAndDelete(id).exec();
    return {
      code: 200,
      msg: 'success',
      data: result,
    };
  }

  //请求全部数据
  async getAllMemoryInfo() {
    const total = await this.MemoryInfoModel.find()
      .select('score price id')
      .exec();
    return {
      code: 200,
      msg: 'success',
      data: total,
    };
  }
}
